<?php
/**
 * DolphinGTK - phpGtk framework
 *
 * @package    DolphinGTK
 * @author     Askarov Ruslan
 * @copyright  Askarov Ruslan (c) 2010.
 * @link       http://groups.google.com/group/dolphingtk
 * @license    http://www.opensource.org/licenses/gpl-license.php GPL
 * @version    0.1
 * @since      PHP v.: 5.2.1
 * @subpackage desktop
 * @category   library
 * @filesource
 */

final class Mysql
{
  private $conn_id;
  public  $result;
  public  $my_query;
  private $db_host;
  private $db_user;
  private $db_pass;
  private $db_name;


  public function __construct($db_host, $db_user, $db_pass, $db_name)
  {
    if( $db_host && $db_user && $db_pass && $db_name )
    {
      $this->db_host = $db_host;
      $this->db_user = $db_user;
      $this->db_pass = $db_pass;
      $this->db_name = $db_name;
    }
    else
    {
      self::display_err("Введите данные для работы с БД");
      exit;
    }
  }


  private function display_err( $error )
  {
    if( $this->my_query ) {
      $query = "{$this->my_query}\n";
    }
    print "Error\n{$error}\n{$query}";
    exit;
  }




  public function set_charset($charset) {
    if( !empty( $charset ) ) {
      $this->query("SET NAMES $charset");
    }
  }




  public function connect()
  {
    $conn_id = @mysql_connect($this->db_host, $this->db_user, $this->db_pass);

    if(!$conn_id) {
      $this->display_err('Соединение с Базами данных отсутствует!');
    }
    else $this->conn_id = $conn_id;

    $sel_db = @mysql_select_db($this->db_name, $this->conn_id);
    if(!$sel_db) $this->display_err('Не удается выбрать Базу данных!');
    else return true;
  }




  public function query($query)
  {
    $this->my_query = $query;

    $this->result = @mysql_query($query, $this->conn_id);

    if( !$this->result ) {
      $this->display_err(@mysql_error($this->conn_id));
    }
    else {
      return true;
    }
  }




  public function num() {
    return @mysql_num_rows($this->result);
  }




  public function insert_id() {
    return @mysql_insert_id($this->conn_id);
  }




  public function free()  {
    @mysql_free_result($this->result);
  }




  public public function escape($str)
  {
    if( ini_get('magic_quotes_runtime') == false )
    {
      if(is_array($str))
      {
        foreach($str as $key => $value)
        {
          $key   = mysql_escape_string($key);
          $value = mysql_escape_string($value);

          $str[$key] = $value;
        }

        return $str;
      }
      else
      {
        return mysql_escape_string($str);
      }
    }
    else
    {
      return $str;
    }
  }




  public function result( $i = 0 )
  {
    $this->query($this->my_query);
    $obj = @mysql_fetch_array($this->result);
    return $obj[$i];
  }




  public function fetch()
  {
    while( $res = @mysql_fetch_assoc($this->result) ):
      foreach($res as $key => $value):
      $res[$key] = $value;
      endforeach;
    $result[] = $res;
    endwhile;

    return $result;
  }




  public function where($where = false)
  {
    if(is_array($where)) {
      $where = $this->escape($where);

      foreach($where as $key => $value):
      if(is_numeric($key))
      {
        $key = "id";
        $or ++;
      }
      $end_where[] = " `$key`='$value' ";
      endforeach;

      return  'where ' . implode( (( $or == count($where) ) ? ' or ' : ' and '), $end_where);
    }
  }




  public function insert($table, $array = false, $exception = false)
  {
    if($exception) {
      foreach($exception as $key):
        unset($array[$key]);
      endforeach;
    }

    $array = $this->escape( $array );

    if( count($array) > 0 && !empty($table) ) {
      $this->query( "insert into `".$table."` (`".implode('`, `', array_keys($array))."`)
      values ('".implode("' , '", array_values($array))."');" );
    }
  }




  public function delete($table, $where)
  {
    $this->query( "delete from `$table` " . $this->where( $where ) );
  }




  public function update($table, $array, $where = false, $exception = false)
  {
    if($exception) {
      foreach($exception as $key):
        unset($array[$key]);
      endforeach;
    }

    if(count($array) > 0) {
      $array = $this->escape($array);

      foreach($array as $key => $value):
      $data[] = " `$key`='$value' ";
      endforeach;
      $this->query( "update `$table` set " . implode(', ', $data) . $this->where($where) );
    }
  }




  public function set_like( $array, $where = false )
  {
    foreach( $array as $key => $value )
    {
      $i ++;
      $r .= " `$key` like '$value' ";

      if( count($array) > 1 && count($array) < $i )
      {
        $r .= $r.' and ';
      }
    }

    $this->set_like = $r;
  }




  public function select($table, $where = false, $limit = false, $order = false)
  {

    if( $this->set_like ) {
      $set_like = 'and '. $this->set_like;
      unset($this->set_like);
    }

    if($limit) {
      $limit =  " limit ".START_PAGE.", ".END_PAGE;
    }

    if($order) {
      $order =  " order by $order";
    }

    $conv_where = $this->where($where);

    $this->query( "select *from `$table` " . $conv_where . $set_like . $order . $limit);
    $result = $this->fetch();

    if($limit) {
      $this->query( "select count(*) from `$table` " . $conv_where . $set_like );
      $obj = @mysql_fetch_array($this->result);
      $num = $obj[0];
    }
    else
      $num = $this->num();

    return array(
      "result" => $result, "num" => $num
    );
  }




  public function db_size()
  {
    $this->query("SHOW TABLE STATUS;");
    $dbsize = 0;

    foreach( $this->fetch() as $value )
    {
      $dbsize += $value['Data_length'] + $value['Index_length'];
    }

    $dbsize = round( ($dbsize / 1024), 0);
    return $dbsize;
  }




  public function optimize()
  {
    $this->query("SHOW TABLES;");
    $returns = array();

    foreach( $this->fetch() as $t => $tablename )
    {
      $table = $tablename['Tables_in_'.$this->db_name];
      $this->my_query = "OPTIMIZE TABLE `$table`;";
      $returns[$table] = $this->result(3);
    }

    return $returns;
  }





  public function disconnect() {
    if($this->conn_id) {
      mysql_close($this->conn_id);
    }
  }

}
?>